package com.yiyuan.app.filter;

import com.guaike.core.entity.api.TokenLocalCache;
import com.guaike.core.entity.constant.HttpHeaderConstant;
import com.guaike.core.entity.enums.ErrorCodeEnum;
import com.guaike.core.entity.exception.ApiException;
import com.guaike.core.redis.helper.LoginHelper;
import com.guaike.core.web.helper.RequestSignHelper;
import com.yiyuan.app.entity.result.AppUser;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Slf4j
public class LoginFilter implements Filter {

    private RedissonClient redissonClient;


    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }


    private static final String[] WHITE_URLS = new String[]{"/doc.html", "/webjars/bycdao-ui", "/swagger-resources", "/v2/api-docs"};

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url = request.getRequestURI();
        String[] var6 = WHITE_URLS;
        int var7 = var6.length;
        String uri;
        for (int var8 = 0; var8 < var7; ++var8) {
            uri = var6[var8];
            if (url.contains(uri)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        String accessToken = request.getHeader("AccessToken");
        AppUser user = LoginHelper.getUserFromCache(this.redissonClient, accessToken);

        if (RequestSignHelper.isNoLogin(url)) {
            servletRequest.setAttribute(HttpHeaderConstant.HEADER_NAME_USERID, Objects.nonNull(user) ? -1 : null);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (Objects.isNull(user)) {
            throw new ApiException(ErrorCodeEnum.ERROR_SYS_INVALID_TOKEN.getCode(), ErrorCodeEnum.ERROR_SYS_INVALID_TOKEN.getDesc());
        }
        String clientId = request.getHeader("cid");
        Long tokenExpire = TokenLocalCache.getTokenExpire(clientId);
        LoginHelper.refreshLoginInfo(redissonClient, accessToken, Objects.isNull(tokenExpire) ? 3600 : tokenExpire);
        servletRequest.setAttribute(HttpHeaderConstant.HEADER_NAME_USERID, -1);
        filterChain.doFilter(servletRequest, servletResponse);

    }
}
